<template> 
	<div class="app-container">
		<el-card class="operate-container" shadow="never">
			<span style="font-weight:bold;font-size: x-large;">|&nbsp;广告位</span>
		</el-card>
		<el-card class="filter-container" shadow="never">
			<div>
				<i class="el-icon-search"></i>
				<span>筛选搜索</span>
				<el-button style="float:right" type="primary" @click="handleSearchList()" size="small">
					查询搜索
				</el-button>
				<el-button style="float:right;margin-right: 15px" @click="handleResetSearch()" size="small">
					重置
				</el-button>
			</div>
			<div style="margin-top: 15px">
				<el-form :inline="true" :model="listQuery" size="small" label-width="140px">
					<el-form-item label="广告名称：">
						<el-input v-model="listQuery.name" class="input-width" placeholder="广告名称"></el-input>
					</el-form-item>
					<!-- <el-form-item label="广告位置：">
						<el-select v-model="listQuery.type" placeholder="全部" clearable class="input-width">
							<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="到期时间：">
						<el-date-picker class="input-width" v-model="listQuery.endTime" value-format="yyyy-MM-dd" type="date" placeholder="请选择时间">
						</el-date-picker>
					</el-form-item> -->
				</el-form>
			</div>
		</el-card>
		<el-card class="operate-container" shadow="never">
			<i class="el-icon-tickets"></i>
			<span>数据列表</span>
			<el-button size="mini" class="btn-add" @click="handleAdd()" v-show="addFlag">添加</el-button>
		</el-card>
		<div class="table-container">
			<!-- @selection-change="handleSelectionChange" -->
			<el-table ref="homeAdvertiseTable" :data="list" style="width: 100%;" 
			 v-loading="listLoading" border>
				<!-- <el-table-column type="selection" width="60" align="center"></el-table-column> -->
				<el-table-column label="编号" width="120" align="center">
					<template slot-scope="scope">{{scope.row.id}}</template>
				</el-table-column>
				<el-table-column label="广告名称" align="center">
					<template slot-scope="scope">{{scope.row.name}}</template>
				</el-table-column>
				<el-table-column label="广告位置" width="200" align="center">
					<template slot-scope="scope">{{scope.row.type | formatType}}</template>
				</el-table-column>
				<el-table-column label="广告图片" width="200" align="center">
					<template slot-scope="scope"><img style="height: 80px" :src="scope.row.pic"></template>
				</el-table-column>
				<el-table-column label="长图详情" width="200" align="center">
					<template slot-scope="scope"><img style="height: 80px" :src="scope.row.url"></template>
				</el-table-column>
				<el-table-column label="分类编号" width="120" align="center">
					<template slot-scope="scope">{{scope.row.categoryId}}</template>
				</el-table-column>
				<el-table-column label="商品编号" width="120" align="center">
					<template slot-scope="scope">{{scope.row.productId}}</template>
				</el-table-column>
				<el-table-column label="文章编号" width="120" align="center">
					<template slot-scope="scope">{{scope.row.subjectId}}</template>
				</el-table-column>
				<el-table-column label="文章类型" width="120" align="center">
					<template slot-scope="scope">{{scope.row.subjectType | formatSubjectType}}</template>
				</el-table-column>
				<el-table-column label="排序" width="120" align="center">
					<template slot-scope="scope">{{scope.row.sort}}</template>
				</el-table-column>
				<!-- <el-table-column label="时间" width="220" align="center">
					<template slot-scope="scope">
						<p>开始时间：{{scope.row.startTime | formatTime}}</p>
						<p>到期时间：{{scope.row.endTime | formatTime}}</p>
					</template>
				</el-table-column> -->
				<el-table-column label="是否显示" width="120" align="center">
					<template slot-scope="scope">
						<el-switch @change="handleUpdateStatus(scope.$index, scope.row)" :active-value="1" :inactive-value="0" v-model="scope.row.status">
						</el-switch>
					</template>
				</el-table-column>


				<el-table-column label="操作" width="120" align="center">
					<template slot-scope="scope">
						<el-button size="mini" type="text" @click="handleUpdate(scope.$index, scope.row)">编辑
						</el-button>
						<el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!--<div class="batch-operate-container">
			 <el-select size="small" v-model="operateType" placeholder="批量操作">
				<el-option v-for="item in operates" :key="item.value" :label="item.label" :value="item.value">
				</el-option>
			</el-select>
			 <el-button style="margin-left: 20px" class="search-button" @click="handleBatchOperate()" type="primary" size="small">
				确定
			</el-button> 
		</div>
		<div class="pagination-container">
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes,prev, pager, next,jumper"
			 :page-size="listQuery.pageSize" :page-sizes="[10,15,50]" :current-page.sync="listQuery.pageNum" :total="total">
			</el-pagination>
		</div> -->
		<el-card class="operate-container" shadow="never">
			<span style="font-weight:bold;font-size: x-large;">|&nbsp;栏目推荐</span>
		</el-card>
		<el-card class="filter-container" shadow="never">
			<div class="table-container" v-loading="loading" border>
				<!-- @selection-change="handleSelectionChange1" -->
				<el-table v-loading="loading" :data="recommendList" >
					<!-- <el-table-column type="selection" width="55" align="center" /> -->
					<el-table-column label="id" align="center" prop="id" v-if="false" />
					<el-table-column label="栏目名称" align="center" prop="recommendName" />
					<el-table-column label="栏目类型" align="center" prop="recommendType" />
					<el-table-column label="商品/资讯编号" align="center" prop="recommendId" />
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
						<template slot-scope="scope">
							<el-button size="mini" type="primary" @click="handleUpdate1(scope.row)">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 添加或修改栏目推荐对话框 -->
				<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
					<el-form ref="form" :model="form" :rules="rules" label-width="120px">
						<el-form-item label="栏目名称" prop="recommendName">
							<el-input v-model="form.recommendName" placeholder="请输入栏目名称" :disabled="true" />
						</el-form-item>
						<el-form-item label="栏目类型" prop="recommendType">
							<el-input v-model="form.recommendType" placeholder="请输入栏目类型" :disabled="true" />
						</el-form-item>
						<el-form-item style="margin-bottom: 0;">
							<span>{{form.tips}}</span>
						</el-form-item>
						<el-form-item label="商品/资讯编号" prop="recommendId" :inline-message="true">
							<el-input v-model="form.recommendId" placeholder="请输入商品/资讯编号" />
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button type="primary" @click="submitForm">确 定</el-button>
						<el-button @click="cancel">取 消</el-button>
					</div>
				</el-dialog>
			</div>
		</el-card>
	</div>
</template>
<script>
	import {
		fetchList,
		updateStatus,
		deleteHomeAdvertise
	} from '@/api/homeAdvertise';
	import {
		listRecommend,
		getRecommend,
		delRecommend,
		addRecommend,
		updateRecommend
	} from "@/api/centers/recommend";
	import {
		formatDate
	} from '@/utils/date';
	// import store from '@/store';
	// const storeId = store.getters && store.getters.storeId;
	const defaultListQuery = {
		pageNum: 1,
		pageSize: 10,
		name: null,
		type: 6,
		endTime: null,
		// storeId: storeId
	};
	const defaultRecommendTypeOptions = [{
			label: '资讯',
			value: 1
		},
		{
			label: '商品',
			value: 2
		}
	];
	const defaultTypeOptions = [{
		label: '首页-第2个轮播图',
		value: 6
	}];
	export default {
		name: 'homePageList',
		data() {
			var validateRecommendId = (rule, value, callback) => {
				if (value !== '') {
					var c = ";"; // 要计算的字符
					var regex = new RegExp(c, 'g'); // 使用baig表示整个字符串都要匹配du
					var result = value.match(regex);
					var count = !result ? 0 : result.length;
					console.log(c + " 的数量为 " + count);
					if (this.form.recommendName == '今日科普') {
						if (count != 0) {
							callback(new Error('仅可输入1个编号'))
						} else {
							callback()
						}
					} else if (this.form.recommendName == '秒杀&拼团') {
						if (count > 1) {
							callback(new Error('可输入2个编号，使用英文;隔开，按照输入顺序排序'))
						} else {
							callback()
						}
					} else if (this.form.recommendName == '精品课程') {
						if (count > 3) {
							callback(new Error('可输入4个编号，使用英文;隔开，按照输入顺序排序'))
						} else {
							callback()
						}
					} else if (this.form.recommendName == '玩酷好物') {
						if (count > 3) {
							callback(new Error('可输入4个编号，使用英文;隔开，按照输入顺序排序'))
						} else {
							callback()
						}
					} else if (this.form.recommendName == '猜你喜欢') {
						if (count > 2) {
							callback(new Error('可输入3个编号，使用英文;隔开，按照输入顺序排序'))
						} else {
							callback()
						}
					} else {
						callback();
					}
				} else {
					callback();
				}
			}
			return {
				addFlag: true,
				listQuery: Object.assign({}, defaultListQuery),
				typeOptions: Object.assign({}, defaultTypeOptions),
				list: null,
				total: null,
				listLoading: false,
				multipleSelection: [],
				operates: [{
					label: "删除",
					value: 0
				}],
				operateType: null,
				//栏目推荐
				// 查询参数
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 表单参数
				form: {
					tips: undefined,
				},
				// 表单校验
				rules: {
					recommendId: [{
						validator: validateRecommendId,
						trigger: 'change'
					}, {
						pattern: /^([1-9]+[0-9;]+\d+)$|^([1-9]\d*)$/,
						message: "请输入正确格式",
						trigger: "blur"
					}, ],
				},
				queryParams: {
					// pageNum: 1,
					// pageSize: 10,
					recommendName: undefined,
					recommendType: undefined,
					recommendLimit: undefined,
					recommendId: undefined,
					// storeId: undefined
				},
				loading: false,
				recommendList: null,
				multipleSelection1: [],
			}
		},
		created() {
			this.getList();
			this.getList1();
		},
		filters: {
			formatType(type) {
				if (type === 6) {
					return '首页-第2个轮播图';
				}
			},
			formatStore(type) {
				if (type === 0) {
					return '平台轮播图';
				} else {
					return type;
				}

			},
			formatSubjectType(subjcetType) {
				if (subjcetType === 1) {
					return '其它';
				} else if (subjcetType === 0) {
					return '科普';
				}
			},
			formatTime(time) {
				if (time == null || time === '') {
					return 'N/A';
				}
				let date = new Date(time);
				return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
			},
			formatRecommendType(type) {
				if (type === 2) {
					return '商品';
				} else if (type === 1) {
					return '资讯';
				}
			},
		},
		methods: {
			handleResetSearch() {
				this.listQuery = Object.assign({}, defaultListQuery);
			},
			handleSearchList() {
				this.listQuery.pageNum = 1;
				this.getList();
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			handleSizeChange(val) {
				this.listQuery.pageNum = 1;
				this.listQuery.pageSize = val;
				this.getList();
			},
			handleCurrentChange(val) {
				this.listQuery.pageNum = val;
				this.getList();
			},
			handleUpdateStatus(index, row) {
				this.$confirm('是否要修改上线/下线状态?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateStatus(row.id, {
						status: row.status
					}).then(response => {
						this.getList();
						this.$message({
							type: 'success',
							message: '修改成功!'
						});
					});
				}).catch(() => {
					this.$message({
						type: 'success',
						message: '已取消操作!'
					});
					this.getList();
				});
			},
			handleDelete(index, row) {
				this.deleteHomeAdvertise(row.id);
			},
			handleBatchOperate() {
				if (this.multipleSelection < 1) {
					this.$message({
						message: '请选择一条记录',
						type: 'warning',
						duration: 1000
					});
					return;
				}
				let ids = [];
				for (let i = 0; i < this.multipleSelection.length; i++) {
					ids.push(this.multipleSelection[i].id);
				}
				if (this.operateType === 0) {
					//删除
					this.deleteHomeAdvertise(this.multipleSelection[i].id);
				} else {
					this.$message({
						message: '请选择批量操作类型',
						type: 'warning',
						duration: 1000
					});
				}
			},
			handleAdd() {
				this.$router.push({
					path: '/marking/addHomePage'
				})
			},
			handleUpdate(index, row) {
				this.$router.push({
					path: '/marking/updateHomePage',
					query: {
						id: row.id
					}
				})
			},
			getList() {
				this.listLoading = true;
				fetchList(this.listQuery).then(response => {
					this.listLoading = false;
					this.list = response.data.records;
					if (this.list && this.list.length > 4) {
						this.addFlag = false;
					} else {
						this.addFlag = true;
					}
					this.total = response.data.total;
				})
			},
			deleteHomeAdvertise(ids) {
				this.$confirm('是否要删除该广告?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let params = new URLSearchParams();
					params.append("ids", ids);
					deleteHomeAdvertise(ids).then(response => {
						this.getList();
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
					});
				})
			},
			//栏目推荐
			getList1() {
				this.loading = true;
				listRecommend(this.queryParams).then(response => {
					console.log(response)
					this.loading = false;
					this.recommendList = response.data;
				})
			},
			handleSelectionChange1(val) {
				this.multipleSelection1 = val;
			},
			// 表单重置
			reset() {
				this.form = {
					id: undefined,
					recommendName: undefined,
					recommendType: undefined,
					recommendLimit: undefined,
					recommendId: undefined,
					storeId: undefined
				};
				this.resetForm("form");
			},
			/** 修改按钮操作 */
			handleUpdate1(row) {
				// this.reset();
				const id = row.id || this.ids
				getRecommend(id).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "编辑栏目推荐";
					this.form.tips = '仅可输入1个编号';
					if (row.recommendName == "今日科普") {
						this.form.tips = "仅可输入1个编号";
					} else if (row.recommendName == "秒杀&拼团") {
						this.form.tips = "可输入2个编号，使用英文;隔开，第1个为秒杀商品编号，第2个为拼团商品编号，无编号输入0";
					} else if (row.recommendName == "精品课程") {
						this.form.tips = "可输入4个编号，使用英文;隔开，按照输入顺序排序";
					} else if (row.recommendName == "玩酷好物") {
						this.form.tips = "可输入4个编号，使用英文;隔开，按照输入顺序排序";
					} else if (row.recommendName == "猜你喜欢") {
						this.form.tips = "可输入3个编号，使用英文;隔开，按照输入顺序排序";
					}
				});
			},
			/** 提交按钮 */
			submitForm: function() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.id != undefined) {
							updateRecommend(this.form).then(response => {
								if (response.code === 200) {
									this.$message({
										type: 'success',
										message: '修改成功'
									});
									this.getList1();
									this.open = false;
								} else {
									// this.msgError(response.msg);
								}
							});
							// } else {
							//   addRecommend(this.form).then(response => {
							//     if (response.code === 200) {
							//       this.msgSuccess("新增成功");
							//       this.open = false;
							//       this.getList();
							//     } else {
							//       this.msgError(response.msg);
							//     }
							//   });
						}
					}
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				// this.reset();
			},
		}
	}
</script>
<style scoped>
	.input-width {
		width: 203px;
	}
</style>
